<?php

class _login
{
    public $defaultFrom = '/';
	public $userinfo = array();

	public function initc()
	{
		$userinfo = $this->isLogin();
		if ($userinfo) {
			$this->userinfo = $userinfo;
		}
	}

	//是否登录
	public function isLogin()
	{
		$rs = User::getUserCookie();
		return !empty($rs) ? $rs : FALSE;
	}

	//是否登录, 接口
	public function iisLogin()
    {
        $rs = User::getUserCookie();
        if (!empty($rs)) {
            User::setUserCookie($rs, $rs['expire']);
            $rs = ['unid' => $rs['unid']];
        }
        Response::success($rs);
    }

	//登录
	public function index()
	{
	    $from = Request::Get('from');
        $reg_from = Request::Get('reg_from');
	    //FileLog::ini('error')->info($from, 'login');
	    if (empty($from) || strpos($from, 'user_login') || strpos($from, 'user_register') || strpos($from, 'user_logout')) {
	        $from = urlencode($this->defaultFrom);
        } else {
            $from = urldecode($from);
        }
        
        $from = ltrim($from, '/');

		if (Request::isPost()) {
			//todo 防止重复提交
			$mobile = Request::Post('mobile');
			$username = Request::Post('username');
			$password = Request::Post('password');
			$remember_me  = Request::Post('remember_me');
			//$from  = Request::Post('from');
			$expire = $remember_me ? 86400*7 : 0;

			$user = User::verifyUserLogin($username, $password);
			if ($user) {
				//写入cookie
				User::setUserCookie($user, $expire);

				//登录成功
                User::afterLogin($user['unid']);
                Response::success(['from' => $from], '登陆成功');
			} else {
                Response::error('用户名或密码错误, 请重新登录');
			}
		} else {
            View::$arrTplVar['from'] = $from;
            View::$arrTplVar['reg_url'] = '/user_register?reg_from='.$reg_from;
			View::display('login');
		}
	}
}